package de.klingbeil.hhc.client.controller;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import de.klingbeil.hhc.client.ItemProxy;
import de.klingbeil.hhc.client.event.ItemChangedEvent;
import de.klingbeil.hhc.client.handler.ItemDataHandler;
import de.klingbeil.hhc.client.model.ItemModelData;
import de.klingbeil.hhc.client.view.View;

public class ItemEditorController implements Controller {
	private final ItemEditorView view;
	private final ItemDataHandler itemHandler;
	private EventBus eventBus;

	public interface ItemEditorView extends View {
		void setOnClickAddItemCallback(OnClickAddItemCallback callback);
	}

	public interface OnClickAddItemCallback {
		void addItem(String description, String price);
	}

	@Inject
	public ItemEditorController(ItemEditorView view,
			ItemDataHandler itemHandler, EventBus eventBus) {
		this.view = view;
		this.itemHandler = itemHandler;
		this.eventBus = eventBus;
		this.view.setOnClickAddItemCallback(createOnClickAddItemCallback());
	}

	private OnClickAddItemCallback createOnClickAddItemCallback() {
		OnClickAddItemCallback callback = new OnClickAddItemCallback() {
			@Override
			public void addItem(String description, String price) {
				itemHandler.persist(description, createAddItemReceiver());
			}

		};
		return callback;
	}

	private Receiver<ItemProxy> createAddItemReceiver() {
		Receiver<ItemProxy> receiver = new Receiver<ItemProxy>() {
			@Override
			public void onSuccess(ItemProxy itemProxy) {
				eventBus.fireEvent(new ItemChangedEvent(ItemModelData
						.from(itemProxy)));
			}

			@Override
			public void onFailure(ServerFailure error) {
			}
		};
		return receiver;
	}

	@Override
	public View getView() {
		return view;
	}
}
